﻿using System;
using LinFu.IoC;
using CoreEx.Services;

namespace CoreEx.Common.Repository
{
    public static class ObjectExtensions
    {
        private static readonly IStateTrackerRepository _stateTrackerRepository;

        static ObjectExtensions()
        {
            var serviceContainer = ServiceLocator.Container;
            _stateTrackerRepository = serviceContainer.GetService<IStateTrackerRepository>();
        }

        public static bool IsDirty<T>(this T target) where T:class
        {            
            return GetState(target).State != StateType.NotModified;
        }

        public static IObjectState GetState<T>(this T target) where T:class
        {
            var stateTracker = _stateTrackerRepository.GetStateTrackerByTarget(target);
            if (stateTracker == null)
                throw new ArgumentOutOfRangeException("target", target, "State tracker not found");
            return stateTracker.GetState(target);
        }

    }
}
